<?php

/**
 * 商品管理
 *
 * @author birdy <freebirdy@foxmail.com>
 * @link http://www.aiyuangong.com
 */

namespace app\seller\controller;

class Goods extends \app\common\controller\Seller
{

    //出售中的商品列表
    function index($type = 'online')
    {
        $where = [];

        $where['store_id'] = $this->store_id;

        $stc_id = $this->request->get('stc_id', 0, 'intval');
        if ($stc_id > 0) {
            $where['goods_stcids'] = array('like', '%,' . $stc_id . ',%');
        }

        $keyword = $this->request->get('keyword', '', 'trim');
        if ($keyword != '') {
            $search_type = $this->request->get('search_type', 0, 'intval');
            switch ($search_type) {
                case 1:
                    $where['goods_serial'] = array('like', '%' . $keyword . '%');
                    break;
                case 2:
                    $where['id'] = intval($keyword);
                    break;
                default:
                    $where['goods_name'] = array('like', '%' . $keyword . '%');
                    break;
            }
        }

        $page = $this->request->get('curpage', 1, 'intval');
        $data = rpc('seller/goods/'.$type, [$where, $page, 10]);
        
        switch ($type) {
            case 'online' :
                $url = 'seller/goods/index';
                $this->assign('type', 'online');
                break;
            case "offline";
                $url = 'seller/goods/offline';
                $this->assign('type', 'offline');
                break;
        }
        $option = ['var_page' => 'curpage', 'path'=>url($url), 'query' => $query];
        $rs = \Page::make($data['goods_list'], 10, $page, $data['total'], false, $option);
        $this->assign('pager', $rs->appends(input('get.'))->render());
        
        $store_goods_class = reset_by_key($this->get_store_goods_class(), 'id');
        $this->assign("store_goods_class", $store_goods_class);
        $this->assign('url', $url);
        $this->assign('left_nav', $type);
        return view('index', $data);
    }
    
    //仓库中的商品
    function offline()
    {
        return $this->index('offline');
    }

    //出售中的商品
    function online()
    {
        return $this->index('online');
    }

    //设置广告词
    function ad_word()
    {
        if ($this->request->isPost()) {
            $common_id = $this->checkRequestCommonId(input('post.commonid', ''));
            $commonid_array = explode(',', $common_id);
            $where = [
                'id' => array('in', $commonid_array),
                'store_id' => $this->store_id
            ];
            $update = ['goods_jingle' => input('post.g_jingle', '', 'trim')];
            $return = rpc('seller/goods/update', [$where, $update]);
            if ($return) {
                //添加操作日志
                $this->recordSellerLog('设置广告词，平台货号：' . $common_id);
                showDialog('广告词设置成功', 'reload', 'succ');
            } else {
                showDialog('广告词设置失败', 'reload');
            }
        }
        $commonid = $this->checkRequestCommonId(input('get.commonid', ''));
        $this->view->assign('commonid', $commonid);
        return view();
    }
    
    /**
     * 分类选择
     */
    public function cate()
    {
        $commonid = input('commonid/d');
        if ($commonid > 0) {
            $this->assign('edit', $commonid);
            $this->assign('url', '/?s=seller/goods/modify&commonid='.$commonid);
            $this->assign('left_nav', 'online');
        } else {
            $this->assign('url', '/?s=seller/goods/modify');
            $this->assign('left_nav', 'goods_add');
        }
        
        $store_class = $this->getStoreClass();
        $this->assign("store_class", $store_class);
        $this->assign('step', 1);
        return view();
    }

    /**
     * 添加商品
     * @return type
     */
    public function modify()
    {
        $commonid = input('commonid/d', 0);
        $cate_id = input('cate_id/id');
        if ($commonid > 0) {
            $common = rpc("common/common/one", ['goods_common', ['id' => $commonid, 'store_id' => $this->store_id]]);
            if (!$common) {
                $this->error('商品不存在');
            }

            $goods_array = $this->db_lists('goods', ['commonid' => $commonid, 'store_id' => $this->store_id], ['field' => 'id,goods_marketprice,goods_price,goods_storage,goods_serial,goods_storage_alarm,goods_spec']);
            $common['goods_storage'] = array_sum(array_column($goods_array, 'goods_storage'));
            $common['spec_name'] = unserialize($common['spec_name']);
            $common['spec_value'] = unserialize($common['spec_value']);
            $common['goods_image_thumb'] = img_url($common['goods_image'], 360);

            // 取得商品规格的输入值
            $sp_value = [];
            if (!empty($goods_array)) {

                // to do 取得已选择了哪些商品的属性

                $spec_checked = array();
                foreach ($goods_array as $k => $v) {
                    $a = unserialize($v['goods_spec']);
                    if (!empty($a)) {
                        foreach ($a as $key => $val) {
                            $spec_checked[$key]['id'] = $key;
                            $spec_checked[$key]['name'] = $val;
                        }
                        $matchs = array_keys($a);
                        sort($matchs);
                        $id = str_replace(',', '', implode(',', $matchs));
                        $sp_value ['i_' . $id . '|marketprice'] = $v['goods_marketprice'];
                        $sp_value ['i_' . $id . '|price'] = $v['goods_price'];
                        $sp_value ['i_' . $id . '|id'] = $v['id'];
                        $sp_value ['i_' . $id . '|stock'] = $v['goods_storage'];
                        $sp_value ['i_' . $id . '|alarm'] = $v['goods_storage_alarm'];
                        $sp_value ['i_' . $id . '|sku'] = $v['goods_serial'];
                    }
                }
                $this->assign('spec_checked', $spec_checked ? : false);
            }
            
            $this->assign('edit', 1);
            $this->assign('sp_value', $sp_value ? : false);
            if (!$cate_id) {
                $cate_id = $common['gc_id'];
            }
            
            $this->assign('left_nav', 'online');
        } else {
            $cate_id = input('cate_id/id');
            if (!$cate_id) { //未选择分类，跳到分类选择
                return redirect(url('seller/goods/cate'));
            }
            $common = ['goods_commend' => 1, 'goods_state' => 1];
            $this->assign('left_nav', 'goods_add');
            $this->assign('step', 2);
        }

        $this->setClassInfo($cate_id);

        $plate = $this->db_lists('store_plate', ['store_id' => $this->store_id], ['field' => 'plate_id,plate_name,plate_position'], 'group_arr_key', ['plate_position']);
        $this->assign('plate', $plate);


        // 小时分钟显示
        $hour_array = array('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23');
        $this->assign('hour_array', $hour_array);
        $minute_array = array('00', '05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55');
        $this->assign('minute_array', $minute_array);


        // 实例化店铺商品分类模型
        $store_goods_class = reset_by_key($this->get_store_goods_class(), 'id');
        $this->assign("store_goods_class", $store_goods_class);

        //处理商品所属分类
        $store_goods_class_tmp = array();
        if (!empty($store_goods_class)) {
            foreach ($store_goods_class as $k => $v) {
                $store_goods_class_tmp[$v['id']] = $v;
                if (is_array($v['_child'])) {
                    foreach ($v['_child'] as $son_k => $son_v) {
                        $store_goods_class_tmp[$son_v['id']] = $son_v;
                    }
                }
            }
        }

        $common['goods_stcids'] = trim($common['goods_stcids'], ',');
        $goods_stcids = empty($common['goods_stcids']) ? [] : explode(',', $common['goods_stcids']);
        $goods_stcids_tmp = $goods_stcids_new = [];
        if (!empty($goods_stcids)) {
            foreach ($goods_stcids as $k => $v) {
                $stc_parent_id = $store_goods_class_tmp[$v]['parent_id'];
                //分类进行分组，构造为array('1'=>array(5,6,8));
                if ($stc_parent_id > 0) {//如果为二级分类，则分组到父级分类下
                    $goods_stcids_tmp[$stc_parent_id][] = $v;
                } elseif (empty($goods_stcids_tmp[$v])) {//如果为一级分类而且分组不存在，则建立一个空分组数组
                    $goods_stcids_tmp[$v] = [];
                }
            }
            foreach ($goods_stcids_tmp as $k => $v) {
                if (!empty($v) && count($v) > 0) {
                    $goods_stcids_new = array_merge($goods_stcids_new, $v);
                } else {
                    $goods_stcids_new[] = $k;
                }
            }
        }
        $this->assign('store_class_goods', $goods_stcids_new);

        $this->assign('goods', $common);
        return view();
    }

    protected function setClassInfo($id)
    {
        $map = [
            'store_id' => $this->store_id,
            'class_2' => $id
        ];

        $bindClass = rpc('common/common/one', ['store_bind_class', $map]);
        if (!$bindClass) {
            $this->error('您选择的分类不存在，或没有选择到最后一级，请重新选择分类。');
        }

        $goods_class = \Fields::getById('goods_class', $id);
        $parent = \Fields::getById('goods_class', $goods_class['pid']);
        $goods_class['tag_name'] = $parent['name'] . " >" . trim($goods_class['name']);
        $goods_class['tag_value'] = $parent['name'] . "," . $goods_class['name'];
        $this->assign('goods_class', $goods_class);

        $specValue = $this->db_lists('spec_value', ['gc_id' => $id, 'store_id' => $this->store_id], ['order' => 'sp_id asc,sp_value_id asc'], 'group_arr_key', 'sp_id');
        $spec = \Fields::getById('goods_spec');
        $spec = reset_by_key($spec, 'sp_id');

        $specList = [];
        foreach ($specValue as $k => $v) {
            if (isset($spec[$k])) {
                $specList[$k] = $spec[$k];
                $specList[$k]['value'] = $v;
            }
        }
        $this->assign('sign_i', count($specList));
        
        $this->assign('spec_list', $specList ?: false);
    }

    /**
     * 商品图片管理
     * @return type
     */
    function images()
    {
        $commonid = input("id/d", 0);
        $gc = rpc("common/common/one", ['goods_common', ['id' => $commonid, 'store_id' => $this->store_id], ['field' => 'goods_image,spec_value']]);
        $goods = array_unique($this->db_lists('goods', ['store_id' => $this->store_id, 'commonid' => $commonid], ['field' => 'id,color_id'], 'array_column', 'color_id'));
        $gc['spec_value'] = unserialize($gc['spec_value']);
        $color_type_id = config('city_spec_id');
        if (isset($gc['spec_value'][$color_type_id])) {
            $color = $gc['spec_value'][$color_type_id];
        } else {
            $color = [0 => '统一设置'];
        }

        $images = $this->db_lists('goods_images', ['store_id' => $this->store_id, 'commonid' => $commonid], ['order' => 'is_default desc, id asc'], 'group_arr_key', 'color_id');
        if (!$images) {
            $this->assign('step', 3);
            $this->assign('left_nav', 'goods_add');
        } else {
            $this->assign('left_nav', 'online');
        }
        foreach ($color as $k => $v) {
            if (!isset($images[$k])) {
                $type = 'goods_add';
                $images[$k] = [
                        [
                        'is_default' => 1,
                        'goods_image' => $gc['goods_image'],
                        'thumb' => img_url($gc['goods_image'], 360)
                    ],
                        ['is_default' => 0], ['is_default' => 0], ['is_default' => 0], ['is_default' => 0]
                ];
            } else {
                foreach ($images[$k] as $k1 => $one) {
                    $images[$k][$k1]['thumb'] = img_url($one['goods_image'], 360);
                }
                $type = 'goods_edit';
                $count = count($images[$k]);
                if ($count < 5) {
                    $leave = 5 - $count;
                    while ($leave --) {
                        $images[$k][] = ['is_default' => 0];
                    }
                }
            }
        }
                
        foreach ($images as $k=>$v) {
            if (!isset($color[$k])) {
                unset($images[$k]);
            }
        }

        $this->assign('goods_images', $images);
        $this->assign('color', $color);
        $this->assign('type', $type);
        return view();
    }

    function images_save()
    {
        if ($this->request->isPost()) {
            try {
                $commonid = input("commonid/d", 0);
                $gc = rpc("common/common/one", ['goods_common', ['id' => $commonid, 'store_id' => $this->store_id], ['field' => 'goods_image,spec_value']]);
                if ($gc) {
                    $imagesAll = input('post.img/a');
                    $dataAll = [];
                    foreach ($imagesAll as $sp_value_id => $images) {
                        $has_default = 0;
                        $data = [];
                        foreach ($images as $one) {
                            if ($one['name']) {
                                $default = $one['default'] ? 1 : 0;
                                $data[] = [
                                    'store_id' => $this->store_id,
                                    'color_id' => intval($sp_value_id),
                                    'commonid' => $commonid,
                                    'goods_image' => $one['name'],
                                    'goods_image_sort' => $one['sort'],
                                    'is_default' => $has_default ? 0 : $one['default']
                                ];
                                if ($default) { //确保只有一个默认
                                    $has_default = true;
                                }
                            }
                        }

                        if (!$data) {
                            if ($type == "goods_add") {
                                $this->error('至少选择一张主图');
                            } else {
                                showDialog('至少选择一张主图');
                            }
                        } else {
                            //没设置默认图片的时候，默认设置第一张为默认
                            if (!$has_default) {
                                $data[0]['is_default'] = 1;
                            }
                        }

                        $dataAll = array_merge($dataAll, $data);
                    }

                    rpc('common/common/delete', ['goods_images', ['store_id' => $this->store_id, 'commonid' => $commonid]]);
                    rpc('common/common/create', ['goods_images', $dataAll, true]);

                    $type = input('post.type', 'goods_edit');
                    if ($type == "goods_add") {
                        return redirect(url('seller/goods/create_ok?id=' . $commonid));
                    } else {
                        showDialog('图片设置成功', url('seller/goods/index'), 'succ');
                    }
                }
            } catch (Exception $ex) {
                //to do exception
            }
        }
    }

    /**
     * 添加商品
     * @return type
     */
    function create_ok()
    {
        $commonid = input("id/d", 0);
        $goods = rpc("common/common/one", ['goods', ['commonid' => $commonid, 'store_id' => $this->store_id], ['field' => 'id']]);
        if ($goods) {
            $this->assign('step', 4);
            $this->assign('left_nav', 'goods_add');
            return view('', ['goods_id' => $goods['id']]);
        }
    }

    /**
     * 商品添加存储
     */
    function save()
    {
        if ($this->request->isPost()) {            
            $time = time();
            $data = input('post.');
            // 验证表单
            $rule = [
                "g_name|商品名称" => "require|length:3,50",
                "g_price|商品价格" => "require|float",
            ];
            $validate = new \think\Validate($rule);
            if (!$validate->check($data)) {
                $this->error($validate->getError() ?: '参数错误');
            }

            // 分类信息
            $goods_class = \Fields::getById('goods_class', $data['cate_id']);
            //to do 检测分类的可靠性
            
            $store_info = rpc('common/common/one', ['store', ['id' => $this->store_id]]);

            $common_array = array();
            $common_array['goods_name'] = $data['g_name'];
            $common_array['goods_jingle'] = $data['g_jingle'];
            $common_array['gc_id'] = intval($goods_class['id']);
            $common_array['gc_id_1'] = intval($goods_class['pid']);
            $common_array['gc_id_2'] = intval($goods_class['id']);
            $common_array['gc_id_3'] = 0;
            $common_array['gc_name'] = $goods_class['name'];

            $common_array['type_id'] = isset($goods_class['type_id']) ? $goods_class['type_id'] : 0;
            $common_array['goods_image'] = $data['image_path'];
            $common_array['goods_price'] = floatval($data['g_price']);
            $common_array['goods_marketprice'] = floatval($data['g_marketprice']);
            $common_array['goods_costprice'] = floatval($data['g_costprice']);
            $common_array['goods_discount'] = floatval($data['g_discount']);
            $common_array['goods_unit'] = $data['g_unit'];
            $common_array['goods_serial'] = $data['g_serial'];
            $goods_storage_alarm = intval($data['g_alarm']);
            $common_array['goods_storage_alarm'] = ($goods_storage_alarm < 0 || $goods_storage_alarm > 255) ? 0 : $goods_storage_alarm;
            $common_array['goods_body'] = isset($data['editorValue']) ? $data['editorValue'] : '';
            $common_array['goods_commend'] = intval($data['g_commend']) ? 1 : 0;

            $g_state = intval($data['g_state']);
            $common_array['goods_state'] = ($store_info['store_state'] != 1) ? 0 : intval($data['g_state']);            // 店铺关闭时，商品下架
            if (isset($data['starttime'])) {
                $common_array['goods_selltime'] = strtotime($data['starttime']) + intval($data['starttime_H']) * 3600 + intval($data['starttime_i']) * 60;
            } else {
                $common_array['goods_selltime'] = 0;
            }
            $common_array['goods_verify'] = (config('goods_verify') == 1) ? 10 : 1;
            $common_array['goods_vat'] = intval($data['g_vat']) ? 1 : 0;

            $prov = intval($data['province']);
            $areacode = intval($data['areacode']);
            $common_array['areacode'] = $areacode ?: $prov;
            $common_array['store_id'] = $this->store_id;
            $common_array['store_name'] = $store_info['name'];

            //品牌
            $common_array['brand_id'] = 0;  // to do 品牌
            $common_array['brand_name'] = ''; // to do 品牌
            //属性
            $common_array['goods_attr'] = ''; // to do 属性
            $common_array['mobile_body'] = ''; // to do 手机序列化保存手机端商品描述数据
            //规格数据处理
            $common_array['spec_name'] = is_array($data['spec']) ? serialize($data['sp_name']) : serialize(null);
            $common_array['spec_value'] = is_array($data['spec']) ? serialize($data['sp_val']) : serialize(null);
            $common_array['spec_value_desc'] = get_arr_vals($data['sp_val'], 3);

            //物流信息
            $common_array['transport_id'] = 0;  // to do 运费模板
            $common_array['transport_title'] = ''; // to do 运费模板
            $common_array['goods_freight'] = floatval($data['g_freight']);

            //查询店铺商品分类
            $goods_stcids_arr = array();
            if (!empty($data['sgcate_id'])) {
                $sgcate_id_arr = array();
                foreach ($data['sgcate_id'] as $k => $v) {
                    $sgcate_id_arr[] = intval($v);
                }
                $sgcate_id_arr = array_unique($sgcate_id_arr);
                $store_goods_class = $this->db_lists('store_goods_class', [
                    'store_id' => $this->store_id,
                    'id' => ['in', $sgcate_id_arr],
                    'state' => 1
                ]);
                if (!empty($store_goods_class)) {
                    foreach ($store_goods_class as $k => $v) {
                        if ($v['id'] > 0) {
                            $goods_stcids_arr[] = $v['id'];
                        }
                        if ($v['parent_id'] > 0) {
                            $goods_stcids_arr[] = $v['parent_id'];
                        }
                    }
                    $goods_stcids_arr = array_unique($goods_stcids_arr);
                    sort($goods_stcids_arr);
                }
            }
            if (empty($goods_stcids_arr)) {
                $common_array['goods_stcids'] = '';
            } else {
                $common_array['goods_stcids'] = ',' . implode(',', $goods_stcids_arr) . ','; // 首尾需要加,
            }

            $common_array['plateid_top'] = intval($data['plate_top']) > 0 ? intval($data['plate_top']) : '';
            $common_array['plateid_bottom'] = intval($data['plate_bottom']) > 0 ? intval($data['plate_bottom']) : '';

            $common_array['is_virtual'] = 0;  //to do virtual
            $common_array['virtual_indate'] = 0;  //to do virtual
            $common_array['virtual_limit'] = 10; //to do virtual
            $common_array['virtual_invalid_refund'] = 0; //to do virtual
            $common_array['is_fcode'] = 0;  //to do fcode
            $common_array['is_appoint'] = 0;  //to do 预约
            $common_array['appoint_satedate'] = ''; //to do 预约

            $common_array['is_presell'] = 0;  //to do 预售
            $common_array['presell_deliverdate'] = ''; //to do 预售

            $common_array['is_own_shop'] = in_array($this->store_id, explode(',', config('own_shop_ids'))) ? 1 : 0;
            
            $common_id = input('commonid/d', 0);
            $turn_image = false; //跳转标识
            $submitOk = false;   //数据提交标识
            $isEdit = false;     //是否编辑模式
            if ($common_id > 0) {
                $old = rpc('common/common/total', ['goods_common', ['store_id' => $this->store_id, 'id' => $common_id]]);
                if (!$old) {
                    $this->error('商品不存在');
                }
                rpc('common/common/update', ['goods_common', ['store_id' => $this->store_id, 'id' => $common_id], $common_array]);
                $goods_ids = $this->db_lists('goods', ['store_id' => $this->store_id, 'commonid' => $common_id], ['field'=>'id'], 'array_column', 'id');
                $submitOk = true;
                $isEdit   = true;
            } else {
                $common_array['goods_addtime'] = $time;
                $common_id = rpc('common/common/create', ['goods_common', $common_array]);
                if ($common_id > 0) {
                    $submitOk = true;
                }
                $goods_ids = [];
            }
            
            
            // 保存数据
            if ($submitOk) {
                // 生成的商品id（SKU）
                if (isset($data['spec']) && $data['spec']) {
                    foreach ($data['spec'] as $value) {
                        $goods = array();
                        $goods['goods_name'] = $common_array['goods_name'] . ' ' . implode(' ', $value['sp_value']);
                        $goods['goods_jingle'] = $common_array['goods_jingle'];
                        $goods['store_id'] = $this->store_id;
                        $goods['store_name'] = $store_info['name'];
                        $goods['gc_id'] = $common_array['gc_id'];
                        $goods['gc_id_1'] = $common_array['gc_id_1'];
                        $goods['gc_id_2'] = $common_array['gc_id_2'];
                        $goods['gc_id_3'] = $common_array['gc_id_3'];
                        $goods['brand_id'] = $common_array['brand_id'];
                        $goods['goods_price'] = $value['price'];
                        $goods['goods_promotion_price'] = $value['price'];
                        $goods['goods_marketprice'] = $value['marketprice'] == 0 ? $common_array['goods_marketprice'] : $value['marketprice'];
                        $goods['goods_unit'] = $common_array['goods_unit'];
                        $goods['goods_serial'] = $value['sku'];
                        $goods['goods_storage_alarm'] = intval($value['alarm']);
                        $goods['goods_spec'] = serialize($value['sp_value']);
                        $goods['goods_storage'] = $value['stock'];
                        $goods['goods_image'] = $common_array['goods_image'];
                        $goods['goods_state'] = $common_array['goods_state'];
                        $goods['goods_verify'] = $common_array['goods_verify'];
                        $goods['goods_addtime'] = $time;
                        $goods['goods_edittime'] = $time;
                        $goods['areacode'] = $common_array['areacode'];
                        $goods['color_id'] = intval($value['color']);
                        $goods['transport_id'] = $common_array['transport_id'];
                        $goods['goods_freight'] = $common_array['goods_freight'];
                        $goods['goods_vat'] = $common_array['goods_vat'];
                        $goods['goods_commend'] = $common_array['goods_commend'];
                        $goods['goods_stcids'] = $common_array['goods_stcids'];
                        $goods['is_virtual'] = $common_array['is_virtual'];
                        $goods['virtual_indate'] = $common_array['virtual_indate'];
                        $goods['virtual_limit'] = $common_array['virtual_limit'];
                        $goods['virtual_invalid_refund'] = $common_array['virtual_invalid_refund'];
                        $goods['is_fcode'] = $common_array['is_fcode'];
                        $goods['is_appoint'] = $common_array['is_appoint'];
                        $goods['is_presell'] = $common_array['is_presell'];
                        $goods['is_own_shop'] = $common_array['is_own_shop'];
                        if (isset($value['goods_id']) && $value['goods_id'] > 0) {
                            $goods_id = intval($value['goods_id']);
                            $pos = array_search($goods_id, $goods_ids);
                            if ($rs !== false) {
                                rpc('common/common/update', ['goods', ['id'=>$goods_id], $goods]);
                                if ($common_array['goods_attr']) {
                                    //to do 属性 新增商品商品与属性对应
                                }
                                unset($goods_ids[$pos]);
                            }
                        } else {
                            $turn_image = true;
                            $goods['commonid'] = $common_id;
                            $goods_id = rpc('common/common/create', ['goods', $goods]);
                            if ($common_array['goods_attr']) {
                                //to do 属性 新增商品商品与属性对应
                            }
                        }
                    }
                } else {
                    $goods = array();
                    $goods['goods_name'] = $common_array['goods_name'];
                    $goods['goods_jingle'] = $common_array['goods_jingle'];
                    $goods['store_id'] = $this->store_id;
                    $goods['store_name'] = $store_info['name'];
                    $goods['gc_id'] = $common_array['gc_id'];
                    $goods['gc_id_1'] = $common_array['gc_id_1'];
                    $goods['gc_id_2'] = $common_array['gc_id_2'];
                    $goods['gc_id_3'] = $common_array['gc_id_3'];
                    $goods['brand_id'] = $common_array['brand_id'];
                    $goods['goods_price'] = $common_array['goods_price'];
                    $goods['goods_promotion_price'] = $common_array['goods_price'];
                    $goods['goods_marketprice'] = $common_array['goods_marketprice'];
                    $goods['goods_unit'] = $common_array['goods_unit'];
                    $goods['goods_serial'] = $common_array['goods_serial'];
                    $goods['goods_storage_alarm'] = $common_array['goods_storage_alarm'];
                    $goods['goods_spec'] = serialize(null);
                    $goods['goods_storage'] = intval($data['g_storage']);
                    $goods['goods_image'] = $common_array['goods_image'];
                    $goods['goods_state'] = $common_array['goods_state'];
                    $goods['goods_verify'] = $common_array['goods_verify'];
                    $goods['goods_addtime'] = $time;
                    $goods['goods_edittime'] = $time;
                    $goods['areacode'] = $common_array['areacode'];
                    $goods['color_id'] = 0;
                    $goods['transport_id'] = $common_array['transport_id'];
                    $goods['goods_freight'] = $common_array['goods_freight'];
                    $goods['goods_vat'] = $common_array['goods_vat'];
                    $goods['goods_commend'] = $common_array['goods_commend'];
                    $goods['goods_stcids'] = $common_array['goods_stcids'];
                    $goods['is_virtual'] = $common_array['is_virtual'];
                    $goods['virtual_indate'] = $common_array['virtual_indate'];
                    $goods['virtual_limit'] = $common_array['virtual_limit'];
                    $goods['virtual_invalid_refund'] = $common_array['virtual_invalid_refund'];
                    $goods['is_fcode'] = $common_array['is_fcode'];
                    $goods['is_appoint'] = $common_array['is_appoint'];
                    $goods['is_presell'] = $common_array['is_presell'];
                    $goods['is_own_shop'] = $common_array['is_own_shop'];

                    if (count($goods_ids) == 1) {
                        rpc('common/common/update', ['goods', ['id' => $goods_ids[0]], $goods]);
                        if ($common_array['goods_attr']) {
                            //to do 属性 新增商品商品与属性对应
                        }
                        $goods_ids = [];
                    } else {
                        $turn_image = true;
                        $goods['commonid'] = $common_id;
                        $goods_id = rpc('common/common/create', ['goods', $goods]);
                        if ($common_array['goods_attr']) {
                            //to do 属性 新增商品商品与属性对应
                        }
                    }
                }
                
                if ($goods_ids) { //删除不需要的规格商品
                    $turn_image = true;
                    rpc('common/common/delete', ['goods', ['id' => ["in", $goods_ids], 'store_id' => $this->store_id]]);
                }

                //to do 商品名称自动添加到scws自定义词库
                // 商品加入上架队列
                if (isset($data['starttime'])) {
                    $selltime = strtotime($data['starttime']) + intval($data['starttime_H']) * 3600 + intval($data['starttime_i']) * 60;
                    if ($selltime > $time) {
                        rpc('common/common/create', ['cron', ['exetime' => $selltime, 'exeid' => $common_id, 'type' => 1]]);
                        //to do　任务计划脚本
                    }
                }

                $tag = $isEdit ? "编辑" : "添加";
                // 记录日志
                $this->recordSellerLog($tag.'商品，平台货号:' . $common_id);

                // to do 生成F码
                
                if ($turn_image) {
                    $this->success('商品'.$tag.'成功', url('seller/goods/images?id=' . $common_id . '&from=goods_add'), [], 1);
                } else {
                    $this->success('商品'.$tag.'成功', url('seller/goods/index'), [], 1);
                }
            } else {
                $this->error('商品发布失败');
            }
        }
    }

    /**
     * 获取店内商品分类
     * @return type
     */
    protected function get_store_goods_class()
    {
        return $this->db_lists('store_goods_class', ['store_id' => $this->store_id, 'state' => 1], ['field' => 'id,name,parent_id'], 'list_to_tree', ['id', 'parent_id']);
    }

    /**
     * 获取商品列表
     */
    public function get_goods_list()
    {
        $commonid = $this->request->get('commonid', 0, 'intval');

        $where = [];
        $where['store_id'] = $this->store_id;
        $where['id'] = $commonid;

        $goodscommon_list = rpc("common/common/one", ['goods_common', $where, ['field' => 'spec_name']]);
        if (empty($goodscommon_list)) {
            return "false";
        }

        unset($where['id']);
        $where['commonid'] = $commonid;

        $field = 'id,goods_spec,store_id,goods_price,goods_serial,goods_storage_alarm,goods_storage,goods_image';

        $goods_list = rpc("seller/goods/lists", [$where, $field]);
        if (empty($goods_list)) {
            return 'false';
        }

        $spec_name = array_values((array) unserialize($goodscommon_list['spec_name']));
        foreach ($goods_list as $key => $val) {
            if ($val instanceof \think\Model) {
                $val = $val->toArray();
                $goods_list[$key] = $val;
            }
            $goods_spec = array_values((array) unserialize($val['goods_spec']));
            $spec_array = array();
            foreach ($goods_spec as $k => $v) {
                $spec_array[] = '<div class="goods_spec">' . $spec_name[$k] . '：<em title="' . $v . '">' . $v . '</em>' . '</div>';
            }
            
            $goods_list[$key]['goods_image'] = img_url($val['goods_image'], 60);
            $goods_list[$key]['goods_spec'] = implode('', $spec_array);
            $goods_list[$key]['alarm'] = ($val['goods_storage_alarm'] != 0 && $val['goods_storage'] <= $val['goods_storage_alarm']) ? 'style="color:red;"' : '';
            $goods_list[$key]['url'] = url('index/goods/detail?goods_id=' . $val['id']);
        }

        return json($goods_list);
    }

    /**
     * 下架
     */
    function unshow()
    {
        $commonid = $this->checkRequestCommonId($this->request->get('commonid', ''));
        $return = rpc('seller/goods/unshow', [$this->store_id, $commonid]);
        if ($return) {
            // to do 更新优惠套餐状态关闭
            // ...
            //操作日志
            $this->recordSellerLog('商品下架，平台货号：' . $commonid);
            showDialog('商品下架成功', getReferer() ? getReferer() : url('seller/goods/index'), 'succ', '', 2);
        } else {
            showDialog('商品下架失败', '', 'error');
        }
    }

    /**
     * 上架
     */
    function show()
    {
        $commonid = $this->checkRequestCommonId($this->request->get('commonid', ''));
        $return = rpc('seller/goods/show', [$this->store_id, $commonid]);
        if ($return) {
            // to do 更新优惠套餐状态关闭
            $this->recordSellerLog('商品上架，平台货号：' . $commonid);
            
            showDialog('商品上架成功', getReferer() ? getReferer() : url('seller/goods/offline'), 'succ', '', 2);
        } else {
            showDialog('商品上架失败', '', 'error');
        }
    }

    /**
     * 删除商品
     */
    function drop()
    {
        $common_id = $this->checkRequestCommonId(input('get.commonid'));
        $return = rpc('seller/goods/delete', [$this->store_id, $common_id]);
        if ($return) {
            // 添加操作日志
            $this->recordSellerLog('删除商品，平台货号：' . $common_id);
            showDialog('商品删除成功', 'reload', 'succ');
        } else {
            showDialog('商品删除失败', '', 'error');
        }
    }

    /**
     * 验证commonid
     */
    private function checkRequestCommonId($common_ids)
    {
        if (!preg_match('/^[\d,]+$/i', $common_ids)) {
            showDialog('参数异常', '', 'error');
        }
        return $common_ids;
    }

}
